package cn.regexp.web.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.regexp.domain.ShopGoods;
import cn.regexp.query.GoodsQuery;
import cn.regexp.service.IGoodsService;
import cn.regexp.utils.JsonResult;
import cn.regexp.utils.RedisKeys;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/query")
    public JsonResult<IPage<ShopGoods>> query(GoodsQuery qo) {
        IPage<ShopGoods> goodsIPage = goodsService.queryGoods(qo);
        return JsonResult.success(goodsIPage);
    }

    @GetMapping("/get")
    public JsonResult<ShopGoods> get(Long goodsId) {
        return JsonResult.success(goodsService.getGoodsById(goodsId));
    }

    @GetMapping("/queryHotGoods")
    public JsonResult<List<ShopGoods>> queryHotGoods() {
        String key = RedisKeys.HOT_GOODS_INFO.join();
        String hotGoodsStr = redisTemplate.opsForValue().get(key);
        List<ShopGoods> hotGoods;
        if (ObjectUtil.isNotEmpty(hotGoodsStr)) {
            hotGoods = JSON.parseArray(hotGoodsStr, ShopGoods.class);
        } else {
            hotGoods = goodsService.queryHotGoods();
        }
        return JsonResult.success(hotGoods);
    }

    @PostMapping("/addViewNum")
    @ApiOperation(value = "添加商品浏览量")
    public JsonResult<String> addViewNum(Long goodsId) {
        if (ObjectUtil.isNotEmpty(goodsId)) {
            ShopGoods goods = goodsService.getById(goodsId);
            goods.setViewNum(goods.getViewNum() + 1);
            goodsService.updateById(goods);
        }
        return JsonResult.success();
    }
}
